package aom.wiindy.service.impl;

import aom.wiindy.mapper.UserMapper;
import com.windy.app.entity.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService{

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //数据库通过passwordEncoder.encode加密密码后再保存
        //1.查询用户
        //2.查询用户角色
        System.out.println("username:"+username);
        com.windy.app.entity.User user = userMapper.selectById(username);
        if (user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<Role> roles = new ArrayList<>();
        roles.add(new Role(1L,"admin","1"));
        user.setRoles(roles);

        List<GrantedAuthority> authorities = new ArrayList<>();
        user.getRoles().forEach(role->authorities.add(new SimpleGrantedAuthority(role.getRoleName())));
        System.out.println(authorities.toString());
        return new User(username,user.getPassword(),authorities);
    }

}
